package com.xxljob.demo.core.scheduler;


import com.xxl.job.core.biz.ExecutorBiz;
import com.xxl.job.core.biz.client.ExecutorBizClient;
import com.xxljob.demo.core.conf.XxlJobAdminConfig;
import com.xxljob.demo.core.thread.JobRegistryMonitorHelper;
import com.xxljob.demo.core.thread.JobScheduleHelper;
import com.xxljob.demo.core.thread.JobTriggerPoolHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;


public class XxlJobScheduler {

    private static final Logger LOGGER = LoggerFactory.getLogger(XxlJobScheduler.class);

    public void init() throws Exception {
        LOGGER.info("XxlJobScheduler.init()");

        //30秒执行一次,维护注册表信息， 判断在线超时时间90s
        LOGGER.info("调度中心执行自动注册线程");
        JobRegistryMonitorHelper.getInstance().start();

        // admin trigger pool start
        LOGGER.info("调度中心执行自动触发线程池初始化");
        JobTriggerPoolHelper.toStart();

        // start-schedule  ( depend on JobTriggerPoolHelper ) 执行调度器
        LOGGER.info("调度中心调度线程启动柜");
        JobScheduleHelper.getInstance().start();
    }

    public void destroy() throws Exception {
        LOGGER.info("XxlJobScheduler.destroy()");
        // stop-schedule
        JobScheduleHelper.getInstance().toStop();
    }

    // ---------------------- executor-client ----------------------
    private static final ConcurrentMap<String, ExecutorBiz> executorBizRepository = new ConcurrentHashMap<String,
            ExecutorBiz>();

    //查找本地缓存
    public static ExecutorBiz getExecutorBiz(String address) throws Exception {

        if (Objects.isNull(address) || address.trim().length() == 0) {
            return null;
        }
        address = address.trim();
        //查找本地缓存
        ExecutorBiz executorBiz = executorBizRepository.get(address);
        if (Objects.nonNull(executorBiz)) {
            return executorBiz;
        }
        executorBiz = new ExecutorBizClient(address, XxlJobAdminConfig.getAdminConfig().getAccessToken());
        executorBizRepository.put(address, executorBiz);
        return executorBiz;
    }
}
